import { ref } from 'vue'

export const useRow = (data) => {
  /** 列表信息 */
  const tableList = ref([data ? JSON.parse(JSON.stringify(data)) : {}])

  /** 增行 */
  const rowAdd = () => {
    tableList.value.push(data ? JSON.parse(JSON.stringify(data)) : {})
  }

  /** 插行 */
  const rowInsert = () => {
    // 获取当前选中的行数
    const num = rowIndexList.value[0].index
    tableList.value.splice(num + 1, 0, data ? JSON.parse(JSON.stringify(data)) : {})
  }

  /** 删行 */
  const rowDelete = () => {
    // 获取选择的索引下标
    const indicesToDelete = rowIndexList.value.map((item) => item.index)
    // 逆序删除，确保索引不影响后续删除
    indicesToDelete.sort((a, b) => b - a)
    // 删除对应的元素
    indicesToDelete.forEach((index) => tableList.value.splice(index, 1))
  }

  /** 复制 */
  const rowCopy = () => {
    rowIndexList.value.forEach((item) => {
      const row = JSON.parse(JSON.stringify(item.row))
      tableList.value.push(row)
    })
  }

  /** 选中行 */
  const rowIndexList = ref([])
  const handleCheckboxChange = (selection) => {
    const rowsIndexList = selection.map((row) => ({
      row,
      index: tableList.value.indexOf(row)
    }))
    rowIndexList.value = rowsIndexList
  }

  return {
    tableList,
    rowIndexList,
    rowAdd,
    rowInsert,
    rowDelete,
    rowCopy,
    handleCheckboxChange
  }
}
